package com.seal.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.seal.comm.utils.Page;
import com.seal.dao.BaseDaoImpl;
import com.seal.dao.IAreaDao;
import com.seal.dto.AreaDto;
import com.seal.model.TArea;

@Service("areaDaoImpl")
@Transactional(readOnly = true)
public class AreaDaoImpl extends BaseDaoImpl implements IAreaDao {

	public void addTArea(TArea ca) throws Exception {
		this.save(ca);
	}

	public void updateTArea(TArea ca) throws Exception {
		this.update(ca);
	}

	public void deleteTArea(TArea ca) throws Exception {
		this.delete(ca);
	}

	public TArea getTAreaById(Long id) throws Exception {
		return (TArea) this.select(TArea.class, id);
	}

	public List<TArea> getAllTArea(AreaDto areaDto, Page page)
			throws Exception {
		StringBuffer hql = new StringBuffer("from TArea t where 1=1 ");

		if (areaDto.getCompanyId() != null) {
			hql.append(" and t.companyId = :companyId");
		}
		
		if (areaDto.getStatus() != null) {
			hql.append(" and t.status = :status");
		}
		
		if (areaDto.getType() != null) {
			hql.append(" and t.type = :type");
		}
		
		if (areaDto.getAreaId() != null) {
			hql.append(" and t.areaId = :areaId");
		}

		if (null != areaDto.getAreaName()
				&& !"".equals(areaDto.getAreaName())) {
			hql.append(" and t.areaName like :areaName");
		}

		Query query = this.getSession().createQuery(hql.toString()+" order by t.areaId,t.id");
		query.setProperties(areaDto);
		if (null != page) {
			query.setFirstResult(page.getFirstResult());
			query.setMaxResults(page.getPageSize());
			String countSql = "select count(t) " + hql.toString();

			Query queryCount = this.getSession().createQuery(countSql);
			queryCount.setProperties(areaDto);
			page.setTotalNumber(Integer.parseInt(queryCount.uniqueResult()
					.toString()));
		}
		return query.list();
	}
}
